<template>
    <el-dialog
            :title="title"
            :visible.sync="isVisible"
            :width="width"
            :before-close="handleClose"
            :lock-scroll="true"
            :close-on-click-modal="false"
            custom-class="pub_dialog"
            @open="getData"
    >
        <VForm
                ref="vformComponents"
                :form="formData.form"
                :options="formData.options"
                :rules="formData.rules"
                :labelWidth="formData.labelWidth"
                :rowspan="rowspan"
                @changeAddress="changeAddress"
                @changeGdArea="changeGdArea"
                @toLoadMethods="toLoadMethods"
        ></VForm>

        <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">{{openType!='detail' ? '取 消':'返 回'}}</el-button>
      <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
    </span>
    </el-dialog>
</template>

<script>
    import { riskShelterDetail,
            riskShelterUpdate,
            riskShelterAdd } from '@/api/risk/shelter'
    import VForm from "@/components/VForm/index";
    export default {
        components: {
            VForm
        },
        props: {
            width: {
                type: String,
                default: "70%",
            },
            title: {
                type: String,
                default: "详情",
            },
            id:{},
            openType:{
                type:String,
                default:"add"
            },
            dialogVisible: {
                type: Boolean,
                default: false
            },
        },
        watch: {
            'width': {
                handler(newVal, oldVal) {
                    console.log('newVal===',newVal, oldVal)
                    let w = this.width.split('%')[0]
                    if(w>=60){
                        this.rowspan = 2
                    }else{
                        this.rowspan = 1
                    }
                },
                deep: true,
                immediate: true
            },
            'typeOptions':{
                handler(newVal, oldVal) {
                    this.formData.options.forEach(t=>{
                        if(t.key=='type'){
                        t.option.data = newVal
                    }
                })
                },
                deep: true,
                immediate: true
            },
          'dataSourceList': {
            handler(newVal, oldVal) {
              this.formData.options.forEach(t => {
                if (t.key == 'dataSourceId') {
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },
          'openType':{
            handler(newVal, oldVal) {
                // 判断是否详情，添加不可编辑标识
                this.formData.options.forEach(t=>{
                  t.disabled = newVal=='detail' ? true : false
                })
            },
            deep: true,
            immediate: true
          }
        },
        computed: {
            isVisible: {
                get() {
                    return this.dialogVisible
                },
                set() {
                    this.close()
                }
            }
        },
        data() {
            return {
                rowspan:1,
                dict:{},
                formData: {
                    form: {
                            name:"",
                            type:"",
                            isIndoor:"",
                            capacity:"",
                            degree:"",
                            useTime:"",
                            useYearLimit:"",
                            manageUnit:"",
                            director:"",
                            directorPhone:"",
                            powerSupply:"",
                            ventilate:"",
                            drainage:"",
                            emergencyEquip:"",
                            reserveMaterials:"",
                            remark:"",
                            dataSource:"",
                            dataSourceId:"",
                            areaCode:[],
                            file:[],
                            address:"",
                            lonLat:"",
                            mapData:null,
                            shelterLevel:""
                        },
                    options: [
                                   {
                                       title: "避难场所名称",
                                       key: "name",
                                       type: "text",
                                   },
                                {
                                    title: "类型",
                                    key: "type",
                                    type: "select",
                                    multiple:false,
                                    option: {
                                        data: this.typeOptions,
                                        props: {
                                            key: "id", // 指定key对应data的字段
                                            label: "label", // 指定label对应data的字段
                                            value: "value", // 指定value对应data的字段
                                        },
                                    },
                                },
                      {
                        title: "等级",
                        key: "shelterLevel",
                        type: "text",
                      },
                                   {
                                       title: "是否室内",
                                       key: "isIndoor",
                                       type: "radio",
                                       option: {
                                         data: [{id:0,label:'否',value:0},{id:1,label:'是',value:1}],
                                         props: {
                                           key: "id", // 指定key对应data的字段
                                           label: "label", // 指定label对应data的字段
                                           value: "value", // 指定value对应data的字段
                                         },
                                       },
                                   },
                                   {
                                       title: "面积（m²）",
                                       key: "area",
                                       type: "text",
                                   },
                                   {
                                       title: "可容纳人数",
                                       key: "capacity",
                                       type: "text",
                                   },
                                   {
                                       title: "抗震设防程度",
                                       key: "degree",
                                       type: "text",
                                   },
                                   {
                                       title: "投入使用时间",
                                       key: "useTime",
                                       type: "date",
                                   },
                                   {
                                       title: "设计使用年限",
                                       key: "useYearLimit",
                                       type: "text",
                                   },
                                   {
                                       title: "主管单位",
                                       key: "manageUnit",
                                       type: "text",
                                   },
                                   {
                                       title: "负责人姓名",
                                       key: "director",
                                       type: "text",
                                   },
                                   {
                                       title: "负责人联系电话",
                                       key: "directorPhone",
                                       type: "text",
                                   },
                                   {
                                       title: "供电情况",
                                       key: "powerSupply",
                                       type: "text",
                                   },
                                   {
                                       title: "通风情况",
                                       key: "ventilate",
                                       type: "text",
                                   },
                                   {
                                       title: "给排水情况",
                                       key: "drainage",
                                       type: "text",
                                   },
                                   {
                                       title: "应急器材",
                                       key: "emergencyEquip",
                                       type: "text",
                                   },
                                   {
                                       title: "储备物资",
                                       key: "reserveMaterials",
                                       type: "text",
                                   },
                                   {
                                       title: "备注",
                                       key: "remark",
                                       type: "text",
                                   },
                                   // {
                                   //     title: "数据来源单位",
                                   //     key: "dataSourceId",
                                   //     type: "select",
                                   //     event: "changeDataSource",
                                   //     multiple:false,
                                   //     option: {
                                   //       data: this.dataSourceList,
                                   //       props: {
                                   //         key: "id", // 指定key对应data的字段
                                   //         label: "name", // 指定label对应data的字段
                                   //         value: "id", // 指定value对应data的字段
                                   //       },
                                   //     },
                                   // },
                                    {
                                      title: "数据来源单位",
                                      key: "dataSource",
                                      type: "text",
                                    },
                                    {
                                        title: "行政区划",
                                        key: "areaCode",
                                        type: "gdAreaSelect",
                                    },
                                   {
                                       title: "附件",
                                       key: "file",
                                       type: "file",
                                       fileType:"file",
                                       listType:"text",
                                       uploadTextTip:"",
                                   },
                                  {
                                    title:'地点选择',
                                    type:'mapPosition',
                                    key:'mapData',
                                  },
                    ],
                    rules: {
                        name :[
                           { required: true, message: '请输入', trigger: 'blur' },
                          {max:64, message: '长度最大为64个字符', trigger: 'blur'}
                        ],
                        type :[
                        ],
                        isIndoor :[
                        ],
                        area :[
                        ],
                        capacity :[
                        ],
                        degree :[
                          {max:32, message: '长度最大为32个字符', trigger: 'blur'}
                        ],
                        useTime :[
                        ],
                        useYearLimit :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        manageUnit :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        director :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        directorPhone :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        powerSupply :[
                          {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        ventilate :[
                          {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        drainage :[
                          {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        emergencyEquip :[
                          {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        reserveMaterials :[
                          {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        remark :[
                          {max:256, message: '长度最大为256个字符', trigger: 'blur'}
                        ],
                        areaCode :[
                          // {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        file :[],
                        mapData :[
                          { required: true, message: '请设置', trigger: 'change' },
                        ],
                    },
                    labelWidth: "140px",
                },
            // 字典
                typeOptions:[],
                dataSourceList:[]
            };
        },
        methods: {
          toLoadMethods(methods) {
            this[methods]()
          },
          changeDataSource(){
            let item = this.dataSourceList.find(t=> t.id == this.formData.form.dataSourceId)
            if(undefined!=item){
              this.formData.form.dataSource = item.name
            }
          },
            initData(){
                     this.formData.form.name = "",
                     this.formData.form.type = "",
                     this.formData.form.isIndoor = "",
                     this.formData.form.capacity = "",
                     this.formData.form.degree = "",
                     this.formData.form.useTime = "",
                     this.formData.form.useYearLimit = "",
                     this.formData.form.manageUnit = "",
                     this.formData.form.director = "",
                     this.formData.form.directorPhone = "",
                     this.formData.form.powerSupply = "",
                     this.formData.form.ventilate = "",
                     this.formData.form.drainage = "",
                     this.formData.form.emergencyEquip = "",
                     this.formData.form.reserveMaterials = "",
                     this.formData.form.remark = "",
                     this.formData.form.dataSource = "",
                     this.formData.form.dataSourceId = "",
                     this.formData.form.areaCode = "",
                     this.formData.form.file = [],
                     this.formData.form.address = "",
                     this.formData.form.lonLat = "",
                     this.formData.form.mapData = null
            },
            getCountySubIndex(cityCode){
                // 中山、东莞截取10位
                let filterList = ['442000000000','441900000000']
                if(filterList.findIndex(t=>t==cityCode)>-1){
                  return 10;
                }
                return 6;
            },
            submitFormat(){
                   this.formData.form.file = JSON.stringify(this.formData.form.file)
            },
            loadFormat(){
                    this.formData.form.file  = this.formData.form.file ? JSON.parse(this.formData.form.file) : []
            },
            getCheckBoxData(value,option,type){
                if(type=="submit"){
                    if(value.length==0){
                        return null
                    }
                    let temp = [];
                    value.forEach(t=>{
                        let item = option.find(x=> x.label == t)
                    if(item!=undefined){
                        temp.push(item.value)
                    }
                })
                    return temp.join(",")
                }else {
                    if(!value){
                        return []
                    }else {
                        let data = value.split(",")
                        let temp = []
                        data.forEach(t=>{
                            let item = option.find(x=> x.value == t)
                        if(item!=undefined){
                            temp.push(item.label)
                        }
                    })
                        return temp
                    }
                }
            },
            positionSubmitFormat(){
              let mapData = this.formData.form.mapData
              if(mapData){
                  this.formData.form.lon = mapData.gpsX
                  this.formData.form.lat = mapData.gpsY
                  this.formData.form.address = mapData.address
                  this.formData.form.areaCode = mapData.towncode
                  if(mapData.towncode){
                      this.formData.form.provinceCode = mapData.towncode.substr(0,2).padEnd(12,'0')
                      this.formData.form.cityCode = mapData.towncode.substr(0,4).padEnd(12,'0')
                      let subIndex = this.getCountySubIndex(this.formData.form.cityCode)
                      this.formData.form.countyCode = mapData.towncode.substr(0,subIndex).padEnd(12,'0')
                  }
                  return true
              }
              return false
            },
            positionLoadFormat(){
                let form = this.formData.form
                let mapData = {}
                if(form.address){
                  mapData.address = form.address
                }
                if(form.lon) {
                  mapData.gpsX = parseFloat(form.lon)
                }
                if(form.lat) {
                  mapData.gpsY = parseFloat(form.lat)
                }
                if(form.areaCode && form.provinceCode && form.cityCode && form.countyCode) {
                  mapData.towncode = form.areaCode
                  this.formData.form.areaCode = [form.provinceCode, form.cityCode, form.countyCode]
                  this.formData.form.mapData = mapData
                  return
                }
                // 空置设置默认经纬度
              this.formData.form.mapData = {gpsX: 113.280637, gpsY: 23.125178}
              console.log("mpap",mapData)
            },
            sure(){
                console.log('sure===',this.formData.form)
                this.$refs.vformComponents.$refs.form.validate().then(res=>{
                    let haveAddress = this.positionSubmitFormat()
                    if(!haveAddress){
                      this.$message.warning("请设置地址信息")
                      return
                    }
                    this.submitFormat()
                    if(this.openType == "add"){
                        this.add()
                    }else{
                        this.update()
                    }
                })
            },
            add(){
                this.formData.form.id = null
                riskShelterAdd(this.formData.form).then(res=>{
                    if(res.code==200){
                    this.$message({
                        message: this.$t('tips.createSuccess'),
                        type: 'success'
                    })
                    this.closeSuccess()
                    }else{
                    this.$message({
                        message: this.$t('tips.systemException'),
                        type: 'error'
                    })
                    }
                })
            },
            update(){
                   riskShelterUpdate(this.formData.form).then(res=>{
                        if(res.code==200){
                        this.$message({
                             message: this.$t('tips.updateSuccess'),
                            type: 'success'
                        })
                        this.closeSuccess()
                      }else{
                        this.$message({
                            message: this.$t('tips.systemException'),
                            type: 'error'
                        })
                     }
                })
            },
            cancel(){
                this.close()
            },
            handleClose(done) {
                done()
                this.close()
            },
            closeSuccess(){
              this.initData()
              this.$refs.vformComponents.$refs.form.resetFields();
                this.$emit('success')
            },
            close(){
                this.initData()
                this.$refs.vformComponents.$refs.form.resetFields();
                this.$refs.vformComponents.$refs.mapPosition[0].reloadMap()
                this.$emit('close')
            },
            getDataSourceData(){
                this.dataSourceList = [{id:"123",name:"部门1"},{id:"456",name:"部门2"}]
            },
            getData(){
              this.getDataSourceData()
              // 获取字典值
              this.typeOptions = []
              this.$commonJs.filterDataDict("riskShelterType",this.typeOptions)
                if(this.openType!="add"){
                    riskShelterDetail(this.id).then(res=>{
                        if(res.code==200){
                            this.formData.form = res.data
                            this.loadFormat()
                            this.positionLoadFormat()
                         }else{
                            this.$message({
                                message: this.$t('tips.systemException'),
                                type: 'error'
                            })
                        }
                    })
                }
            },
            changeAddress(data){
                // console.log(data)
                this.formData.form.mapData = data
                this.formData.form.areaCode = data.areaCode
            },
            changeGdArea(data){
                console.log(data)
            },
        },
    };
</script>

<style lang="scss" scoped>

</style>
